<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>

        let $ = {
            get:function (url, data, fn, type) {
                // 1. 创建xhr对象
                let x = new XMLHttpRequest();
                // 地址栏拼接 -data 对象
                url = url + '?';
                for (item in data) {
                    url += `${item}=${data[item]}&`;
                }
                url = url.slice(0, -1);
                // 2. 打开
                x.open('get', url)
                // 3. 发送
                x.send();
                // 4 监听状态
                x.onreadystatechange = function () {
                    if (x.readyState == 4) {
                        if (x.status >= 200 && x.status < 300) {
                            fn(x.response)
                        }
                    }
                }
            },
            post:function (url, data, fn, type) {
                // 1. 创建xhr对象
                let x = new XMLHttpRequest();

                // 2. 打开
                x.open('post', url)
                let str = Object.keys(data).map(item=>`${item}=${data[item]}&`).join('').slice(0,-1);

                // 3. 发送
                x.setRequestHeader('content-type','application/x-www-form-urlencoded');
                x.send(str);


                // 4 监听状态
                x.onreadystatechange = function () {
                    if (x.readyState == 4) {
                        if (x.status >= 200 && x.status < 300) {
                            fn(x.response)
                        }
                    }
                }
            }
        };


        // ajax 异步获取数据

        $.get('http://127.0.0.1/server',{a:12,b:5},(data)=>{
            console.log(data);
        })

        $.post('http://127.0.0.1/server', { a: 1222, b: 5 }, (data) => {
            console.log(data);
        })

        // $.get(url,data,fn,type);

    </script>
</body>

</html>